package com.jc.business.supplierproduct;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jc.business.base.BaseBusiness;
import com.jc.cds.model.CustomSupplierGoods;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.MD5;
import com.jc.common.util.NumberUtils;
import com.jc.ds.model.SupplierGoods;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SupplierProduct;
import com.jc.ds.model.SupplierProductPrice;
import com.jc.framework.enums.ImageType;
import com.jc.framework.enums.Push;
import com.jc.service.h5.ShopService;
import com.jc.service.model.h5.H5RespModel;
import com.jc.service.model.h5.MallGoods;
import com.jc.service.model.h5.MallSku;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.supplierproductprice.SupplierProductPriceService;


/***
 * 
* @version:
* @Description: 处理供应商产品SKU的相关业务
* @author: zyf
* 2018年11月26日
 */
@Service
public class SupplierProductBusiness extends BaseBusiness{
	
	@Autowired
	private SupplierProductService supplierProductService;
	
	@Autowired
	private SupplierGoodsService supplierGoodsService;
	
	@Autowired
	private SupplierGoodsPictureListService supplierGoodsPictureListService;
	
	@Autowired
	private SupplierProductPriceService supplierProductPriceService;
	
	@Autowired
	private ShopService shopService;
	
	
	@Value("${jingxi.h5.key}")
	private String key;
	@Value("${jingxi.h5.code}")
	private String code;
	
	/***
	* 
	* @Title: 推送产品至H5商城
	* @Description: 每次查询出20条待推送的产品SKU信息，逐条封装推送至H5商城
	* @param 
	* @return void
	* @throws
	*/
	public void pushProducts(int rows) {		
		Page<CustomSupplierGoods> page =  PageHelper.startPage(1, rows);
		Date dd = DateTimeUtil.addMinute(new Date(), -10);
		
		supplierGoodsService.selectGoodsByCreateTime(dd);
		
		if (page != null && page.size() > 0) {
			try {
				for (CustomSupplierGoods goods : page) {
					pushGoods(goods);
				}
			} catch (Exception e) {
				getLOGGER().error("");
			}

		}
	} 
	
	/***
	 * 
	* @Title: pushProduct
	* @Description: 逐个进行产品向H5商城推送，单独作为一个事务处理,防止某一条出现推送错误的时候其它同步成功的也被回滚掉。
	* @param @param prod
	* @return void
	* @throws
	 */
	@Transactional
	public void pushGoods(CustomSupplierGoods goods) {
		if( goods != null ) {
			//推送H5商城并更新推送状态
			//1. 封装报文
			MallGoods mGoods = initMallGoods();
			mGoods.setProductName(goods.getName());
			mGoods.setProductCode(String.valueOf(goods.getId()));
			mGoods.setProductTypeName(goods.getCategoryName());//用小类,就是二级分类
			mGoods.setProductCategoryName(goods.getCategoryParentName());//大分类,在商城叫做商品目录
			mGoods.setStoreName(goods.getSupplierName());
			mGoods.setBrandName(goods.getBrandnamecn());
			mGoods.setShortDesc(goods.getName());
			SupplierGoodsPictureList _pic = new SupplierGoodsPictureList();
			_pic.setImageType(ImageType.ROTATION.getName());
			_pic.setGid(goods.getId());
			List<SupplierGoodsPictureList> _supplierGoodsPictureList = supplierGoodsPictureListService.queryAll(_pic);
			String pics = "";
			for(int i = 0 ; _supplierGoodsPictureList != null && i < _supplierGoodsPictureList.size() ; i++) {
				SupplierGoodsPictureList pico = _supplierGoodsPictureList.get(i);
				if((i + 1) == _supplierGoodsPictureList.size()) {
					pics = pics + pico.getSelfImagePath();
				}else {
					pics = pics + pico.getSelfImagePath() + ";";
				}
			}
			mGoods.setPics(pics);
			//详情图，需要排序
			
			SupplierGoodsPictureList _pic2 = new SupplierGoodsPictureList();
			_pic2.setImageType(ImageType.DETAILS.getName());
			_pic2.setGid(goods.getId());
			_pic2.orderByImageOrder(true);
			List<SupplierGoodsPictureList> _supplierGoodsPictureList2 = supplierGoodsPictureListService.queryAll(_pic2);
			String details = "";
			for(int i = 0 ; _supplierGoodsPictureList2 != null && i < _supplierGoodsPictureList2.size() ; i++) {
				SupplierGoodsPictureList _delail = _supplierGoodsPictureList2.get(i);
				if((i + 1) == _supplierGoodsPictureList2.size()) {
					details = details + _delail.getSelfImagePath();
				}else {
					details = details + _delail.getSelfImagePath() + ";";
				}
			}
			mGoods.setDetails(details);
			//规格组名称
			mGoods.setSkuOptionName(getSkuOptionName(goods.getSpecificationsString()));
			
			/********************************************************************************************/
			List<MallSku> _skulist = new ArrayList<MallSku>();
			SupplierProduct _sp = new SupplierProduct();
			_sp.setGid(goods.getId());
			_sp.setPushStatus(Push.WAIT_PUSH.getName());
			List<SupplierProduct> _productList = supplierProductService.queryAll(_sp);
			for(SupplierProduct sp : _productList) {
				MallSku sku = new MallSku();
				sku.setSkuCode(String.valueOf(sp.getId()));
				sku.setSkuOptionValueName(getSkuOptionValueName(sp.getSpecificationsString()));
				sku.setImageUrl(sp.getSelfProductImagePath());
				//取价格信息
				
				SupplierProductPrice _price = new SupplierProductPrice();
				_price.setSupplierProductId(sp.getId());
				_price.orderById(false);//取最后一条
				List<SupplierProductPrice> priceList = supplierProductPriceService.queryAll(_price);
				if(CollectionUtils.isNotEmpty(priceList)) {
					SupplierProductPrice supplierProductPrice = priceList.get(0);
					sku.setPrice(NumberUtils.getYuanByFen(supplierProductPrice.getMoneyPrice() ));
					sku.setTaobaoPrice(NumberUtils.getYuanByFen(supplierProductPrice.getMoneyPrice() ));
					sku.setCommercePrice(NumberUtils.getYuanByFen(supplierProductPrice.getLeve1Price()));
					sku.setElitesPrice(NumberUtils.getYuanByFen(supplierProductPrice.getLeve2Price() ));
					sku.setCrownPrice(NumberUtils.getYuanByFen(supplierProductPrice.getLeve3Price() ));
					sku.setSupremacyPrice(NumberUtils.getYuanByFen(supplierProductPrice.getLeve4Price() ));
					sku.setCost(NumberUtils.getYuanByFen(supplierProductPrice.getCostPrice()));
					sku.setParentCost(NumberUtils.getYuanByFen(supplierProductPrice.getCostPrice()));
					sku.setWeight("0");
					sku.setInventory(String.valueOf(sp.getInventoryNum()));
				}else {
					getLOGGER().error( sp.getId() +  "这个SKU找不到价格信息");
					return ;
				}
				_skulist.add(sku);
			}
			mGoods.setSkuList(_skulist);
			//2. 推送 并记录日志
				String urls = "product/addProduct";
				String body = JSONObject.toJSONString(mGoods);
				H5RespModel ret = shopService.pushH5(urls, body);
				
				if(StringUtils.equals(ret.getReturnCode(), "0")) {//成功
					
					//更新产品同步状态
					SupplierGoods updateObject = new SupplierGoods();
					Long gid = Long.parseLong(mGoods.getProductCode());
					updateObject.setId(gid);
					updateObject.setExtend1(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT));
					supplierGoodsService.modify(updateObject, false);
					
					//更新SKU同步状态,后面修改为批量更新来提高效率,暂时逐条更新，因为马上要上线
					for(MallSku sk : _skulist) {
						SupplierProduct _p = new SupplierProduct();
						_p.setId(Long.valueOf(sk.getSkuCode()));
						_p.setPushStatus(Push.PUSH_OK.getName());
						supplierProductService.modify(_p, false);
					}
				}else {//失败
					//失败后把添加时间修改为当前时间
					SupplierGoods updateObject = new SupplierGoods();
					Long gid = Long.parseLong(mGoods.getProductCode());
					updateObject.setId(gid);
					//updateObject.setCreateTime(new Date());
					updateObject.setExtend1(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT));
					supplierGoodsService.modify(updateObject, false);
					for(MallSku sk : _skulist) {
						SupplierProduct _p = new SupplierProduct();
						_p.setId(Long.valueOf(sk.getSkuCode()));
						_p.setPushStatus(Push.PUSH_ERROR.getName());
						supplierProductService.modify(_p, false);
					}
				}
		}
		
	}
	
	public String getSkuOptionName(String attrDesc) {
		String ret = "";
		try {
			JSONArray attrNameArray = JSONObject.parseArray(attrDesc);
			for(int i = 0 ; attrNameArray != null && attrNameArray.size() > i ; i++) {
				JSONObject attrNameObject = attrNameArray.getJSONObject(i);
				if( (i+1) == attrNameArray.size()) {
					ret = ret + attrNameObject.getString("name");
				}else {
					ret = ret + attrNameObject.getString("name") + "+";
				}
			}
			return ret;
		}catch(Exception e) {
			return "";
		}
	}
	
	public String getSkuOptionValueName(String attrDesc) {
		String ret = "";
		try {
			JSONArray attrNameArray = JSONObject.parseArray(attrDesc);
			for(int i = 0 ; attrNameArray != null && attrNameArray.size() > i ; i++) {
				JSONObject attrNameObject = attrNameArray.getJSONObject(i);
				if( (i+1) == attrNameArray.size()) {
					ret = ret + attrNameObject.getString("detailName");
				}else {
					ret = ret + attrNameObject.getString("detailName") + "+";
				}
			}
			return ret;
		}catch(Exception e) {
			return "";
		}
	}
	public MallGoods initMallGoods() {
		MallGoods mallGoods = new MallGoods();
		String ts = String.valueOf(new Date().getTime());
		StringBuffer _sign = new StringBuffer();
		_sign.append("code=").append(code).append("&ts=").append(ts).append("&key=").append(key);
		getLOGGER().error("加密前秘钥为: " + _sign.toString());
		String sign = MD5.passmd5(_sign.toString());
		getLOGGER().error("加密后秘钥为: " + sign);
		mallGoods.setCode(code);
		mallGoods.setEncryptedString(sign);
		mallGoods.setTs(ts);
		return mallGoods;
	}

}
